import PateoSearchForm from '@/components/common/PateoSearchForm';
import { filterAuth } from '@/support/common';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Card, Checkbox, message, Table, TableColumnsType, TableProps } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import { ImportModal } from './Modal/importModal';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { ColumnsType } from 'antd/es/table';
import { DATE_HMS } from '@/support/constant/common';
import moment, { Moment } from 'moment';
import { ExpandedDataType } from '@/types/ability';
import { ExpandableConfig, TableRowSelection } from 'antd/es/table/interface';
import { router } from 'umi';
import { ViewModal } from './Modal/viewModal';
import { cloneDeep } from 'lodash';

@connect((state: any) => ({
  basicService: state.basicService,
  loading: state.loading.effects['basicService/getFetchPage'],
  permissions: state.menu.permissions,
}))
export default class BasicService extends PureComponent<any, any> {
  state = {
    formValues: {},
    importModalVisable: false,
    viewModalVisable: false,
    update: false,
    selectKeys: [] as string[],
    isImport: false,
    checkList: [] as any[],
    clickRowData: {},
  };
  componentDidMount() {
    this.fetchPage();
  }
  handleFormReset = () => {
    this.state.formValues = {};
    this.setState({ formValues: this.state.formValues });
  };
  closeModal = (refresh = false) => {
    this.setState({
      importModalVisable: false,
      viewModalVisable: false,
    });
    if (refresh) {
      const { formValues } = this.state;
      this.fetchPage(formValues);
    }
  };
  handleFreshPage = () => {
    this.fetchPage();
  };
  handleTableChange = (pagination: any, filters: any = {}) => {
    const { current, pageSize: pagesize } = pagination;
    this.fetchPage({ current, pagesize });
  };
  fetchPage = (params = {}) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    this.setState({ selectKeys: [] });
    dispatch({
      type: 'basicService/getFetchPage',
      payload: {
        url: '/api/ms-soa-service/v1/service/library/service/list',
        ...params,
        ...formValues,
      },
    });
  };
  rowSelectionOnChange = keys => {
    this.setState({ selectKeys: keys });
    const {
      basicService: {
        pageData: { list, pagination },
      },
    } = this.props;
    (keys.length === list.length || keys.length === 0) &&
      list.forEach(t => {
        const checked = keys.includes(t.id);
        t.children.forEach(y => (y.checked = checked));
      });
  };
  // 全选/取消
  selectAllHandle = (selected, selectedRows, changeRows) => {
    const keys = selectedRows.map(t => t.id);
    this.setState({ selectKeys: keys });
    const {
      basicService: {
        pageData: { list, pagination },
      },
    } = this.props;
    list.forEach(t => {
      t.children.forEach(y => (y.checked = selected));
    });
  };
  // 打开导入
  openImort = () => {
    const {
      basicService: {
        pageData: { list },
      },
    } = this.props;
    const { selectKeys } = this.state;
    const checkList = [] as any[];
    const cloneList = cloneDeep(list);
    cloneList.forEach(t => {
      const filterArr = t.children.filter(y => y.checked);
      if (filterArr.length || (!t.children.length && selectKeys.includes(t.id))) {
        checkList.push({
          ...t,
          children: filterArr,
        });
      }
    });
    if (!checkList.length) return message.warning('请至少选择一条服务');
    this.setState({ checkList, importModalVisable: true });
  };
  expandedRowRender: ExpandableConfig<any>['expandedRowRender'] = record => {
    const { isImport } = this.state;
    const columns: TableColumnsType<ExpandedDataType> = [
      {
        title: '服务接口元素名称',
        dataIndex: 'name',
        render: (value, record, index) => {
          return value ?? '--';
        },
      },
      {
        title: '服务接口元素描述',
        dataIndex: 'desc',
        render: (value, record, index) => {
          return value ?? '--';
        },
      },
      {
        title: '服务接口元素标识符',
        dataIndex: 'flag',
        render: (value, record, index) => {
          return value ?? '--';
        },
      },
    ];
    const rowSelection: TableProps<ExpandedDataType>['rowSelection'] = isImport
      ? {
          hideSelectAll: true,
          selectedRowKeys: record.children.filter(t => t.checked).map(t => t.id),
          onSelect: (childRecord, selected) => {
            childRecord.checked = selected;
            let { selectKeys } = this.state;
            if (record.children.every(t => t.checked)) {
              !selectKeys.includes(record.id) && selectKeys.push(record.id);
            } else {
              selectKeys.includes(record.id) &&
                (selectKeys = selectKeys.filter(key => key !== record.id));
            }
            this.setState({ update: !this.state.update, selectKeys: [...selectKeys] });
          },
        }
      : undefined;
    return (
      <Table
        rowSelection={rowSelection}
        rowKey={'id'}
        columns={columns}
        dataSource={record.children}
        pagination={false}
      />
    );
  };
  render() {
    const { importModalVisable, isImport, selectKeys, checkList, viewModalVisable, clickRowData } =
      this.state;
    const {
      basicService: {
        pageData: { list, pagination },
      },
      loading,
      dispatch,
      location,
    } = this.props;
    const { expandedRowRender, rowSelectionOnChange } = this;

    const columns: ColumnsType<any> = [
      {
        title: '服务ID',
        dataIndex: 'serviceId',
        width: 150,
      },

      {
        title: '服务名称',
        dataIndex: 'serviceName',
        width: 150,
        ellipsis: true,
      },

      {
        title: '上次修改人员账号',
        dataIndex: 'updateName',
        width: 150,
        ellipsis: true,
      },
      {
        title: '上次修改时间',
        dataIndex: 'updateTime',
        width: 150,
        ellipsis: true,
        render: v => (v ? moment(v).format(DATE_HMS) : '--'),
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 120,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '查看',
              key: 'view',
              auth: 'basicService-opt',
              onConfirm: () => {
                this.setState({ viewModalVisable: true, clickRowData: record });
              },
            },
            {
              title: '编辑',
              key: 'edit',
              auth: 'basicService-opt',
              onConfirm: () => {
                router.push('/soaManage/serviceManage/serviceLibrary/editServer');
                sessionStorage.setItem('serviceLibrary_serverData', JSON.stringify(record));
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'basicService-opt',
              Popconfirm: true,
              message: '确认删除该服务吗？',
              onConfirm: () => {
                dispatch({
                  type: 'basicService/postObjWithRes',
                  payload: {
                    url: `/api/ms-soa-service/v1/service/library/service?serviceId=${record.serviceId}`,
                  },
                  callback: res => {
                    if (res.statusCode === '0') {
                      message.success('删除成功');
                      this.fetchPage();
                    }
                  },
                });
              },
            },
          ];
          return <PateoAuthButtons btns={btns} pathname={location.pathname} />;
        },
      },
    ];

    const paginationProps = {
      pageSizeOptions: [10, 20, 50],
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const searchItems = [
      {
        type: 'input',
        title: '服务id',
        key: 'serviceId',
      },
      {
        type: 'input',
        title: '服务名称',
        key: 'serviceName',
      },
    ];

    return (
      <div>
        <Card className="pd0" bordered={false}>
          {/* search form */}
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'basicService/getFetchPage',
              url: '/api/ms-soa-service/v1/service/library/service/list',
              extraArgs: {},
            }}
            dispatchFn={this.fetchPage}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
          />
        </Card>

        <Card className="pd0" bordered={false}>
          {/* add */}
          <div>
            {filterAuth(
              'basicService-opt',
              this.props.permissions,
              this.props.location.pathname,
            ) ? (
              <div className="my_newItem">
                <div style={{ display: !isImport ? 'block' : 'none' }}>
                  <Button
                    type="primary"
                    size="small"
                    onClick={() => this.setState({ isImport: true })}
                  >
                    导入车型
                  </Button>
                  <Button
                    type="primary"
                    size="small"
                    onClick={() => {
                      router.push('/soaManage/serviceManage/serviceLibrary/addServer');
                    }}
                  >
                    新建
                  </Button>
                </div>
                <div style={{ display: isImport ? 'block' : 'none' }}>
                  <Button type="primary" size="small" onClick={() => this.openImort()}>
                    确认导入
                  </Button>
                  <Button
                    size="small"
                    onClick={() => {
                      this.setState({ isImport: false });
                      this.selectAllHandle(false, [], list);
                    }}
                  >
                    取消
                  </Button>
                </div>
              </div>
            ) : null}
          </div>

          {/* table */}
          <Table
            size={'small'}
            rowKey={record => record.id}
            dataSource={list}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            rowSelection={
              isImport
                ? {
                    selectedRowKeys: selectKeys,
                    renderCell: (value, record, index, originNode) => {
                      const childdrenCheckedNum = record.children.filter(t => t.checked).length;
                      const halfChecked =
                        childdrenCheckedNum > 0 && childdrenCheckedNum < record.children.length;
                      return (
                        <Checkbox
                          {...originNode.props}
                          indeterminate={halfChecked}
                          // checked={value}
                        />
                      );
                    },
                    onSelect: (record, selected) => {
                      let { selectKeys } = this.state;
                      if (selected) {
                        selectKeys.push(record.id);
                      } else {
                        selectKeys = selectKeys.filter(key => key !== record.id);
                      }
                      record.children.forEach(t => (t.checked = selected));
                      this.setState({ selectKeys: [...selectKeys] });
                    },
                    onSelectAll: this.selectAllHandle,
                  }
                : undefined
            }
            onChange={this.handleTableChange}
            expandable={{
              childrenColumnName: '_no',
              rowExpandable: record => {
                return record.children.length;
              },
              expandedRowRender,
              expandIcon: props => {
                const { expanded, onExpand, record } = props;
                if (!record.children.length) return null;
                return (
                  <DownOutlined
                    onClick={e => onExpand(record, e)}
                    rotate={expanded ? 180 : 0}
                    onPointerEnterCapture={() => {}}
                    onPointerLeaveCapture={() => {}}
                  />
                );
              },
            }}
            scroll={{ x: 'auto' }}
          />
        </Card>
        <ImportModal
          modalVisible={importModalVisable}
          closeModal={this.closeModal}
          checkList={checkList}
        />
        <ViewModal
          modalVisible={viewModalVisable}
          closeModal={this.closeModal}
          data={clickRowData}
        />
        {/* <ExportModal modalVisible={exportVisible} closeModal={this.closeModal} /> */}
      </div>
    );
  }
}
